#pragma once

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>

class ThreadPool {
private:
    std::atomic<bool> _run;
    std::vector<std::thread> _workers;
    std::queue<std::function<void()>> _taskQueue;
    std::mutex _mutex;
    std::condition_variable _cv;

public:
    ThreadPool() = delete;
    ThreadPool(const ThreadPool &) = delete;
    ThreadPool(ThreadPool &&) = delete;
    ThreadPool &operator=(const ThreadPool &) = delete;

    ThreadPool(uint32_t size);

    template <typename F, typename... Args>
    auto exec(F &&f, Args &&...args) -> std::future<typename std::result_of<F(Args...)>::type>;

    ~ThreadPool();
};

ThreadPool::ThreadPool(uint32_t size)
{
    _run = true;

    for (int i = 0; i < size; i++) {
        _workers.push_back(std::thread([this]() {
            while (_run) {
                std::unique_lock<std::mutex> _lock(_mutex);

                _cv.wait(_lock, [&]() { return !_run || !_taskQueue.empty(); });

                if (!_run) {
                    break;
                }

                if (!_taskQueue.empty()) {
                    auto task = std::move(_taskQueue.front());
                    _taskQueue.pop();
                    task();
                }
            }
        }));
    }
}

template <typename F, typename... Args>
auto ThreadPool::exec(F &&f, Args &&...args) -> std::future<typename std::result_of<F(Args...)>::type>
{
    using returnType = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared<std::packaged_task<returnType()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));

    auto res = task->get_future();
    {
        std::unique_lock<std::mutex> _lock(_mutex);

        _taskQueue.push([task]() { (*task)(); });

        _cv.notify_one();
    }

    return res;
}

ThreadPool::~ThreadPool()
{
    {
        std::unique_lock<std::mutex> _lock(_mutex);

        _run = false;

        _cv.notify_all();
    }

    for (auto &work : _workers) {
        if (work.joinable()) {
            work.join();
        }
    }
}